﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using TombstoneHelper;
using System;
using tumblr.Models;

namespace tumblr.Views
{
    public partial class SearchPage : PhoneApplicationPage
    {
        public SearchPage()
        {
            InitializeComponent();

            DataContext = App.SearchViewModel;
            Loaded += new RoutedEventHandler(SearchPage_Loaded);
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            this.SaveState(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.RestoreState();
        }

        private void SearchPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!App.SearchViewModel.IsDataLoaded)
                App.SearchViewModel.LoadData();
        }

        private void TextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (App.SearchViewModel.SearchCommand.CanExecute(e.Key))
                App.SearchViewModel.SearchCommand.Execute(e.Key);
        }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            var bindingExpr = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
            bindingExpr.UpdateSource();
        }

        private void recentQueryUrls_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (recentQueryUrls.SelectedIndex == -1)
                return;

            App.SearchViewModel.Query = (recentQueryUrls.SelectedValue as SearchQuery).Query;

            if (App.SearchViewModel.SearchCommand.CanExecute(Key.Enter))
                App.SearchViewModel.SearchCommand.Execute(Key.Enter);

            recentQueryUrls.SelectedIndex = -1;
        }
    }
}